﻿
package extremefx.ui {
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.ui.Mouse;		

	/**
	 * @author Marcelo Volmaro
	 */
	public final class CursorManager {
		private static var _inst:CursorManager;
		
		private var _cursor:DisplayObject;
		private var _xOffset:int;
		private var _yOffset:int;
		private var _root:Sprite;
		

		public function CursorManager(pRes:PrivateClass) {}
		
		private static function get _instance():CursorManager{
			if (_inst == null){
				_inst = new CursorManager(new PrivateClass());
			}
			
			return _inst;
		}
		
		public static function init():void {
			_instance._root = UIStage.CURSORS;
		}
		
		/**
		 *  sets display object as cursor ( removes prev cursor automatically)
		 * @param	pCursor  new cursor
		 * @param	pXoffset x offset from mouse position
		 * @param	pYoffset y offset from mouse position
		 */
		public static function setCursor(pCursor:DisplayObject, pXoffset:int = 0, pYoffset:int = 0):void {
			var ins:CursorManager = _instance;
			var root:Sprite = ins._root;
			
			if (ins._cursor) {
				removeCursor();
			}
			
			Mouse.hide();
			
			ins._cursor = pCursor;
			if (pCursor is InteractiveObject) {
				InteractiveObject(pCursor).mouseEnabled = false;
				if (pCursor is DisplayObjectContainer) {
					DisplayObjectContainer(pCursor).mouseChildren = false;
				}
			}
			
			ins._xOffset = pXoffset;
			ins._yOffset = pYoffset;
			
			root.addChild(pCursor);
			root.addEventListener(MouseEvent.MOUSE_MOVE, ins._onMouseMove, false, 0, true);
			
			pCursor.x = int(root.mouseX + pXoffset);
			pCursor.y = int(root.mouseY + pYoffset);
		}
		
		private function _onMouseMove(e:MouseEvent):void {
			_cursor.x = int(_root.mouseX + _xOffset);
			_cursor.y = int(_root.mouseY + _yOffset);
			e.updateAfterEvent();
		}

		/**
		 * removes cursor created by last setCursor() method, restores original system cursor
		 */
		public static function removeCursor():void {
			var ins:CursorManager = _instance;
			var root:Sprite = ins._root;
			
			if (!ins._cursor) return;

			root.removeEventListener(MouseEvent.MOUSE_MOVE, ins._onMouseMove);
			root.removeChild(ins._cursor);
			ins._cursor = null;
			Mouse.show();
		}
	}
}

final class PrivateClass {}